package counter

import (
	"gitee.com/Luna-CY/hui-hui/internal/logger"
	"gitee.com/Luna-CY/hui-hui/internal/toolbox/crontab"
	"github.com/shirou/gopsutil/v3/disk"
	"github.com/shirou/gopsutil/v3/net"
	"os"
	"sync"
)

var once sync.Once
var instance = &Counter{}

// Single 单例
func Single(crontab *crontab.Crontab) *Counter {
	once.Do(func() {
		instance.crontab = crontab
		instance.network.current = make(map[string][2]uint64)
		instance.network.total = make(map[string][2]uint64)

		// 注册系统任务
		if err := instance.crontab.AddSystem("* * * * * *", instance.counter); nil != err {
			logger.GetLogger().Sugar().Errorf("统计服务: 注册系统任务失败: %s", err)

			os.Exit(1)
		}
	})

	return instance
}

type Counter struct {
	crontab *crontab.Crontab // 定时器

	month          int                            // 当前月
	beforeDisks    map[string]disk.IOCountersStat // 统计状态
	beforeNetworks []net.IOCountersStat           // 统计状态

	// 网络IO数据统计
	network struct {
		cm      sync.RWMutex
		current map[string][2]uint64 // 网卡名称 -> [up, down]

		tm    sync.RWMutex
		total map[string][2]uint64 // 网卡名称 -> [up, down]
	}
	disk struct {
		read  uint64 // 磁盘读字节
		write uint64 // 自盘写字节
	}
}
